"use client"
import { useEffect, useState } from "react";
import { CarCard, CustomFilter, Hero, SearchBar, ShowMore } from "@/components";
import { fuels, yearsOfProduction } from "@/constants";
import { HomeProps } from "@/types";
import { fetchCars } from "@/utils";
import Image from "next/image";


export default  function Home() {
  const [allCars, setAllCars] = useState([]);
  const [loading, setLoading] = useState(false);
  const [manufacturer, setManufacturer] = useState("");
  const [model, setModel] = useState("");
  const [fuel, setFuel] = useState("");
  const [year, setYear] = useState(2022);
  const [limit, setLimit] = useState(10);

  const getCars = async ()=>{
    setLoading(true)
   try{
    const result = await fetchCars({
      manufacturer: manufacturer || "",
      year: year || 2022,
      fuel: fuel || "",
      limit:limit || 10,
      model: model || "",
    });

    setAllCars(result)
   }catch(error){
    console.log(error)
   } finally{
    setLoading(false)
   }
   
  }

  useEffect(() => {
    getCars()
  }, [fuel,year,limit,manufacturer,loading,model]);

  const isDataEmpty = !Array.isArray(allCars) || allCars.length < 1 || !allCars;
  

  return (
    <main className="overflow-hidden">
      <Hero />

      <div className='mt-12 padding-x padding-y max-width' id='discover'>
        <div className='home__text-container'>
        <h1 className='text-4xl font-extrabold'>汽车-总览</h1>
            <p>搜索您喜欢的车辆</p>
        </div>
        {/* 筛选 */}
        <div className="home__filters">
          <SearchBar setManuFacturer={setManufacturer} setModel={setModel} />
        {/* 车辆总览 */}
        <div className="home__filter-container">
          <CustomFilter title="fuel" options={fuels} setFilter={setFuel}/>
          <CustomFilter title="year" options={yearsOfProduction} setFilter={setYear}/>
        </div>
        </div>

        {allCars.length > 0 ? (
          <section>
           <div className="home__cars-wrapper">
            {allCars?.map((car) => (
                  <CarCard car={car} />
              ))}
           </div>

              {loading && (
                <div className="mt-16 w-full flex-center">
                  <Image 
                    src="/loader.svg"
                    alt="loader"
                    width={50}
                    height={50}
                    className="object-contain"
                  />
                </div>
              )}

           <ShowMore
              pageNumber={limit || 10}
              isNext={limit  > allCars.length}
              setLimit={setLimit}
            />
          </section>
        ):(
          <div className="home__error-container">
            <h2 className=" text-black text-xl font-bold">搜索失败!,没有这个车辆信息</h2>
            <p>{allCars?.message}</p>
          </div>
        )}

      </div>
    </main>
  );
}
